package com.lingxin.gps.sdk;


import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.pisces.core.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author hdl
 */
public class GpsDeviceClient {

	private static Logger logger = LoggerFactory.getLogger(GpsDeviceClient.class);

	public static String METHOD_GET = "get";
	public static String METHOD_POST = "post";

	/**
	 * 测试环境
	 */
    private String hostName="122.152.213.168:8010";
    private String protocol = "http";
    private String method = METHOD_GET;
    private Map<String, String> params = new HashMap<String, String>();
    private String postData = null;
    
	private String apiPath;
    
    public void setApiPath(String apiPath){
    	this.apiPath = apiPath;
    }

	public void addParams(String key, Object value) {
		params.put(key, String.valueOf(value));
	}
    
//	public void addParams(String key, String value) {
//		params.put(key, value);
//	}
    
    /**
     * 执行API调用
     * @return 返回服务器响应内容
     */
    public String invoke(){
        //拼成URL
        String apiUrl = protocol + "://" + hostName + apiPath;

		int retriedCount = 1;
		int totalRetryCount = 3;
		while (true) {
			try {
				logger.info("正在进行第[" + retriedCount + "]次调用[" + apiUrl + "], 参数：" + JsonKit.toJson(params));
				String response;
				if(method.equals(METHOD_POST)){
					response = HttpKit.post(apiUrl, params, postData);
				}else{
					response = HttpKit.get(apiUrl, params);
				}
				logger.info("调用[" + apiUrl + "]结果:" + response);
				return response;
			} catch (Exception e) {
				e.printStackTrace();
				retriedCount++;

				if (retriedCount > totalRetryCount) {
					logger.error("调用平台接口 " + retriedCount + " 次，没有得到正确的返回值");
					throw new BizException("系统繁忙，请稍后再试");
				}
			}
		}
    }

    
	public void setHostName(String hostName) {
		this.hostName = hostName;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public void setPostData(String postData) {
		this.postData = postData;
	}

	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}
}
